$(function(){
  App.init()
});

var App = {
  heading: {
    'good': "Battle station fully operational",
    'minorproblem': "Minor service disruption",
    'majorproblem': "Major service disruption"
  },

  secondsToUpdate: 31,

  init: function(){
    this.headingElement = $('#statusbar h1')
    this.contentElement = $('.main')
    this.secondsElement = $('#time-to-update')
    this.updatedElement = $('.last-updated')

    $('#tweets').tweet()
    this.request()
  },

  request: function(){
    var handleResponse = function(json){
      App.setStatus(json['status'])
      App.setDayStatuses(json['days'])
      App.updatedElement.text(json['last_updated'])
      App.tick()
    }

    $.getJSON('/status.json?cache=' + Math.random(), handleResponse)
  },

  setStatus: function(status){
    $(document.body).removeClass('good').removeClass('minorproblem').removeClass('majorproblem').addClass(status)
    this.headingElement.text(this.heading[status])
  },

  setDayStatuses: function(data){
    var el = this.contentElement.empty()
    $.each(data, function(index, day){
      var text = day['date']

      if (day['status'] == 'minorproblem') text = text + ' &ndash; minor interruption occurred'
      if (day['status'] == 'majorproblem') text = text + ' &ndash; major interruption occurred'

      el.append('<h3 class="' + day['status'] + '">' + text + '</h3>')
      el.append(day['message'])
    })
  },

  tick: function(){
    if (this.secondsToUpdate <= 0){
      this.secondsToUpdate = 31
      this.request()
    }else{
      this.secondsToUpdate--;
      this.secondsElement.text(this.secondsToUpdate)
      setTimeout(function(){ App.tick() }, 1000)
    }
  }
}